/*
 * @lc app=leetcode.cn id=2 lang=javascript
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let head=new ListNode(null)
    let tail=head
    let add=0
    while(l1||l2){
        if(!l1){
            l1={val:0,next:null}
        }
        if(!l2){
            l2={val:0,next:null}
        }
        let res=(l1.val||0)+(l2.val||0)+add
        add=0
        if(res>=10){
            res-=10
            add=1
        }
        l1=l1.next
        l2=l2.next
        tail.next=new ListNode(res)
        tail=tail.next
    }
    if(add){
        tail.next=new ListNode(add)
    }
    return head.next
};
// @lc code=end

var addTwoNumbers = function(l1, l2) {
    let head = null, tail = null;
    let carry = 0;
    while (l1 || l2) {
        const n1 = l1 ? l1.val : 0;
        const n2 = l2 ? l2.val : 0;
        const sum = n1 + n2 + carry;
        if (!head) {
            head = tail = new ListNode(sum % 10);
        } else {
            tail.next = new ListNode(sum % 10);
            tail = tail.next;
        }
        carry = Math.floor(sum / 10);
        if (l1) {
            l1 = l1.next;//这一步比我的优雅，走到最后一个当l==null，时就不走了
        }
        if (l2) {
            l2 = l2.next;
        }
    }
    if (carry > 0) {
        tail.next = new ListNode(carry);
    }
    return head;
};
